﻿@*
    For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
*@
@{
    Layout = null;
}
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>角色分配权限</title>
    <link href="~/scripts/layui-v2.5.6/layui/css/layui.css" rel="stylesheet" />
    <style>
        .container {
            padding: 15px;
            display: flex;
            justify-content: center;
            min-height: 100vh;
            align-items: center;
        }

        .tree-container {
            width: 300px;
            padding: 10px;
            border-right: 1px solid #e6e6e6;
            background-color: #fff;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            border-radius: 4px;
        }

        .form-container {
            flex: 1;
            padding: 10px 20px;
        }

        body {
            margin: 0;
            background-color: #f2f2f2;
        }

        .btn-container {
            text-align: center;
            margin-top: 20px;
        }
    </style>
</head>
<body>
    @Html.AntiForgeryToken()
    <div class="container">
        <div class="tree-container">
            <div id="ID-tree-demo-showLine"></div>
            <div class="btn-container">
                <button type="button" class="layui-btn layui-btn-normal" id="savePermission">保存权限</button>
            </div>
        </div>
    </div>

    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="~/scripts/layui-v2.5.6/layui/layui.js"></script>
    <script>
        // 获取URL中的roleId参数
        function getQueryVariable(variable) {
            var query = window.location.search.substring(1);
            var vars = query.split("&");
            for (var i = 0; i < vars.length; i++) {
                var pair = vars[i].split("=");
                if (pair[0] == variable) {
                    return pair[1];
                }
            }
            return false;
        }

        // 获取角色ID
        var roleId = getQueryVariable('roleId');

        layui.use(['form', 'tree', 'layer'], function(){
            var form = layui.form;
            var tree = layui.tree;
            var layer = layui.layer;

            // 获取已分配的权限ID
            function getExistingPermissions(callback) {
                if (!roleId) {
                    console.log('未获取到roleId');
                    callback([]);
                    return;
                }
                console.log('正在获取权限，roleId:', roleId);
                $.ajax({
                    url: '/Role/FantianRolePermission',
                    type: 'get',
                    data: { id: roleId },
                    success: function(result) {
                        console.log('获取到的权限ID:', result);
                        callback(result || []);
                    },
                    error: function(xhr, status, error) {
                        console.log('获取权限失败:', error);
                        callback([]);
                    }
                });
            }

            // 获取树形数据并渲染
            function loadAndRenderTree() {
                $.ajax({
                    url: '/Permission/GetTreePermission',
                    type: 'get',
                    data: { ParentId: 0 },
                    success: function(result) {
                        console.log('获取到的树形数据:', result);
                        var treeData = formatTreeData(result);
                        console.log('格式化后的树形数据:', treeData);
                        
                        // 获取已分配的权限，在渲染树之前准备好选中的节点
                        getExistingPermissions(function(existingPermissions) {
                            if (existingPermissions && existingPermissions.length > 0) {
                                console.log('准备设置选中状态，权限IDs:', existingPermissions);
                            }
                            
                            // 渲染树
                            var inst = tree.render({
                                elem: '#ID-tree-demo-showLine',
                                data: treeData,
                                showLine: true,
                                showCheckbox: true,
                                id: 'permissionTree'
                            });

                            // 等待树渲染完成后设置选中状态
                            setTimeout(function() {
                                if (existingPermissions && existingPermissions.length > 0) {
                                    existingPermissions.forEach(function(permId) {
                                        console.log('正在设置权限ID:', permId);
                                        try {
                                            layui.tree.setChecked('permissionTree', permId);
                                        } catch (e) {
                                            console.error('设置权限选中状态失败:', e);
                                        }
                                    });
                                }
                            }, 300);
                        });
                    },
                    error: function(xhr, status, error) {
                        layer.msg('加载权限数据失败，请刷新页面重试', {icon: 2});
                    }
                });
            }

            // 格式化树形数据
            function formatTreeData(data) {
                return data.map(function(item) {
                    return {
                        title: item.permissionName,
                        id: item.id,
                        spread: true,
                        children: item.children ? formatTreeData(item.children) : null
                    };
                });
            }

            // 初始化表单
            form.render();

            // 初始加载树形数据
            loadAndRenderTree();

            // 保存权限按钮点击事件
            $('#savePermission').on('click', function() {
                if (!roleId) {
                    layer.msg('未获取到角色ID，请返回角色列表重试', {icon: 2});
                    return;
                }

                // 获取选中的节点
                var checkedData = tree.getChecked('permissionTree');
                
                // 递归获取所有选中的权限ID
                function getCheckedIds(nodes) {
                    var ids = [];
                    nodes.forEach(function(node) {
                        ids.push(parseInt(node.id));  // 确保ID是数字类型
                        if (node.children && node.children.length > 0) {
                            ids = ids.concat(getCheckedIds(node.children));
                        }
                    });
                    return ids;
                }

                var selectedPermissionIds = getCheckedIds(checkedData);

                if (selectedPermissionIds.length === 0) {
                    layer.msg('请至少选择一个权限', {icon: 2});
                    return;
                }

                // 获取防伪令牌
                var token = $('input[name="__RequestVerificationToken"]').val();

                // 显示加载层
                var loadIndex = layer.load(1, {
                    shade: [0.3, '#fff']
                });

                // 构造FormData对象
                var formData = new FormData();
                formData.append('id', 0);
                formData.append('roleId', parseInt(roleId));
                // 添加每个权限ID
                selectedPermissionIds.forEach(function(id) {
                    formData.append('PermissionId[]', id);
                });

                // 发送请求到后端
                $.ajax({
                    url: '/Role/RolePermission',
                    type: 'POST',
                    data: formData,
                    processData: false,
                    contentType: false,
                    headers: {
                        'RequestVerificationToken': token
                    },
                    success: function(result) {
                        layer.close(loadIndex);
                        // 判断返回值是否为1
                        if (result === 1) {
                            layer.msg('权限分配成功', {icon: 1}, function() {
                                window.location.href = '/Role/GetRole';
                            });
                        } else {
                            layer.msg('权限分配失败', {icon: 2});
                        }
                    },
                    error: function(xhr, status, error) {
                        layer.close(loadIndex);
                        console.error('保存权限失败:', error);
                        layer.msg('操作失败，请重试', {icon: 2});
                    }
                });
            });
        });
    </script>
</body>
</html>